package util

import (
	"github.com/gorilla/mux"
	"net/http"
	"strconv"
)

// 回写json数据
func WriteJson(w http.ResponseWriter, body []byte) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_, _ = w.Write(body)
}

func getParam(r *http.Request, key string) interface{} {
	params := mux.Vars(r)
	return params[key]
}

func GetIntParam(r *http.Request, key string) (int, error) {
	return strconv.Atoi(GetStringParam(r, key))
}

func GetStringParam(r *http.Request, key string) string {
	return getParam(r, key).(string)
}

// 返回成功消息
func Success(data interface{}) ([]byte, error) {
	res := make(map[string]interface{}, 0)
	res["code"] = 0
	res["message"] = "成功"
	res["data"] = data
	return ToJson(res)
}

// 返回失败消息
func Fail(message string, err error) ([]byte, error) {
	res := make(map[string]interface{}, 0)
	res["code"] = -1
	if message == "" {
		message = "失败"
	}
	if err != nil {
		res["message"] = err.Error()
	} else {
		res["message"] = message
	}
	return ToJson(res)
}
